#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <iostream>
#include <string>

#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <signal.h>

void error_handling(const char *message)
{
    perror(message);
    exit(1);
}

void* read_mesg(void* arg)
{
    int lfd = reinterpret_cast<long>(arg);
    while(1)
    {
        char buf[100];
        int ret = read(lfd, buf, 100);
        if (ret > 10)
        {
            char name[10], content[90];
            memcpy(name, buf, 10);
            memcpy(content, buf + 10, 90);

            std::cout << name << ": " << content << std::endl;
        }
        else
        {
            error_handling("read error");
        }
    }

    return nullptr;
}

int main(int argc, char *argv[])
{

    int lfd = socket(PF_INET, SOCK_STREAM, 0);

    sockaddr_in addr_lfd;
    addr_lfd.sin_family = AF_INET;
    addr_lfd.sin_addr.s_addr = inet_addr("43.143.243.218");
    addr_lfd.sin_port = htons(6688);

    int ret = connect(lfd, (sockaddr *)&addr_lfd, sizeof(addr_lfd));
    if (ret == -1)
    {
        error_handling("connect socket error");
        exit(1);
    }

    //用户名
    std::cout << "请输入昵称: " << std::flush;
    std::string name;
    std::getline(std::cin, name);

    pthread_t read_thr;
    pthread_create(&read_thr, NULL, read_mesg, reinterpret_cast<void *>(lfd));
    pthread_detach(read_thr);

    std::string content;
    while (content != "q" && content != "Q")
    {
        content.clear();
        std::getline(std::cin, content);
        if(content == "")
            continue;;

        char mesg[100];
        memcpy(mesg, name.c_str(), 10);
        memcpy(mesg + 10, content.c_str(), 90);

        write(lfd, mesg, 100);
    }

    return 0;
}